﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Data.AID;
using Business.AID;
using Business.AID.Extensions;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Linq;

namespace Presentation.AID.WebPart.Presentation.AID.VWPMeusFormularios
{
    public partial class VWPMeusFormulariosUserControl : UserControl
    {
        private int IdEmployee
        {
            get 
            {
                object obj = ViewState["IdEmployee"];
                return (obj == null) ? 0 : (int)obj;
            }
            set { ViewState["IdEmployee"] = value; }
        }
        private Boolean isException
        {
            get { return SPContext.Current.Web.Groups["Exceções"].ContainsCurrentUser; }
        }
        private int FormCount
        {
            get 
            {
                object obj = ViewState["FormCount"];
                return (obj == null) ? 0 : (int)obj; 
            }
            set { ViewState["FormCount"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SetGridView();
            }
        }

        #region Métodos Privados

        private void SetGridView()
        {
            ColaboradorBO colaboradorBO = new ColaboradorBO();
            Colaborador colaborador = colaboradorBO.GetEmployeeByLogin(SPContext.Current.Web.CurrentUser.LoginName);

            if (colaborador != null)
            {
                IdEmployee = colaborador.Id;
                FormularioBO formularioBO = new FormularioBO();
                List<Formulario> listForm = formularioBO.GetFormsByEmployee(colaborador).OrderByDescending(p => p.Criado.Year).ToList();
                
                FormCount = listForm.Where(p =>p.Criado.Year == DateTime.Now.Year).ToList().Count;

                gdvMeusForms.DataSource = listForm;
                gdvMeusForms.DataBind();

                NewButtonEnable();
            }
            else
            {
                gdvMeusForms.Visible = false;
                lblMsgError.Text = "Usuário não foi encontrado no quem é quem!";
                lblMsgError.Visible = true;
            }
        }
        private void CreateForm(int idEmployee)
        {
            FormularioBO formularioBO = new FormularioBO();

            int maxNum = formularioBO.GetAllFormsByYear().Max(p => p.NumeroFormulario);

            Colaborador colaborador = new ColaboradorBO().GetEmployeeById(idEmployee);

            int proxNum = maxNum + 1;

            Formulario formulario = new Formulario()
            {
                IdColaborador = colaborador.Id,
                Estagio = 4,
                NumeroFormulario = proxNum
            };

            formularioBO.CreateForm(formulario);
            SetGridView();
        }
        private Boolean isUserWithForm()
        {
            if (FormCount == 0)
            {
                return false;
            }
            return true;
        }
        private Boolean isValidPeriod()
        {
            PeriodoAtividadeBO periodBO = new PeriodoAtividadeBO();
            return periodBO.isValidPeriod("Cadastrar");
        }
        private void NewButtonEnable()
        {
            Boolean isPeriod = isValidPeriod();
            Boolean isExcep = isException;
            Boolean isUser = isUserWithForm();

            if ((isValidPeriod() || isException) && !isUserWithForm())
            {
                btnNewForm.Visible = true;
            }
        }

        #endregion

        #region Eventos

        protected void gdvMeusForms_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowIndex = Convert.ToInt32(e.CommandArgument);
            DataKey dtKey = gdvMeusForms.DataKeys[rowIndex];
            int idForm = Convert.ToInt32(dtKey["ID"]);
            
            if (e.CommandName == "Historico")
            {
                Response.Redirect("Historico.aspx?idForm=" + idForm + "&viewer=user");
            }

            if (e.CommandName == "Editar")
            {
                //System.Web.HttpContext.Current.Session["IdForm"] = idForm;
                Response.Redirect("MinhasMetas.aspx?f=" + idForm);
            }
        }
        protected void btnNewForm_Click(object sender, EventArgs e)
        {
            if (IdEmployee != 0)
            {
                CreateForm(IdEmployee);
                btnNewForm.Visible = false;
                SetGridView();
            }
        }

        #endregion

    }
}
